﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.Threading;

namespace RemoteScriptingLibrary
{
    public class SerialDevice
    {
        public static SerialPort serialPort1 = new SerialPort("COM2", 115200, Parity.None, 8, StopBits.One);
        private static Form form = new Form();

        public static bool m_bAppend = true;

        private static string m_sText = string.Empty;

        SerialDevice()
        {
           
        }

        public static string Serial(params string[] _sText)
        {
            return Serial(true, _sText);
        }

        public static string Serial( bool _bIncludeReturn, params string[] _sText)
        {
            myReceivedLines.Clear();
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.Open();
            string sReturnText = ReceiveReturnText(_bIncludeReturn, _sText);

            if (form.IsDisposed) form = new Form();

            form.FormBorderStyle = FormBorderStyle.SizableToolWindow;
            form.TopMost = true;          
            
            if (m_bAppend)
            {
                m_sText += sReturnText + Environment.NewLine + Environment.NewLine;
            }
            else
            {
                m_sText = sReturnText;
            }

            TextBox tb = CreateForm();
            ScrollToEnd(tb);
            serialPort1.Close();
            return sReturnText;
        }

        private static string ReceiveReturnText(bool _bIncludeReturn, string[] _sText)
        {
            foreach (string sText in _sText)
            {
                string sTextTemp = sText;
                if (_bIncludeReturn) sTextTemp += Environment.NewLine;
                serialPort1.Write(sTextTemp);
                Thread.Sleep(50);
            }
            Thread.Sleep(300);
            string sReturnText = string.Join("", myReceivedLines);
            return sReturnText;
        }

        private static void ScrollToEnd(TextBox tb)
        {
            tb.SelectionStart = tb.Text.Length;
            tb.ScrollToCaret();
            tb.Refresh();
        }

        private static TextBox CreateForm()
        {
            TextBox tb = new TextBox();
            tb.Text = m_sText;
            if (form.IsDisposed) form = new Form();
            tb.Multiline = true;
            tb.Dock = DockStyle.Fill;
            tb.Parent = form;
            tb.ScrollBars = ScrollBars.Both;
            if (!form.Visible) form.Show();
            return tb;
        }

        private static List<string> myReceivedLines = new List<string>();

        static void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            var bytesToRead = serialPort1.BytesToRead;
            //myReceivedLines.AddRange(Regex.Split(serialPort1.ReadExisting(), Environment.NewLine));
            myReceivedLines.Add(serialPort1.ReadExisting());

            // Buffer wasn't full. We are at the end of the transmission.
            if (bytesToRead < serialPort1.DataBits)
            {
            }
        }
    }
}
